/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.groupofdoom.beans;

import edu.chl.groupofdoom.entities.User;
import edu.chl.groupofdoom.enums.Rank;
import edu.chl.groupofdoom.jpa.Mapper;
import edu.chl.groupofdoom.support.SupportClass;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 * Controller bean for log-in and register
 *
 * @author Martin Agfjord
 */
@ManagedBean(name = "LoginBean")
@RequestScoped
public class LoginBean implements Serializable {

    private String username = "";
    private String password = "";
    private String email = "";
    private boolean admin;
    private List<String> errors;

    public LoginBean() {
    }

    /**
     * Checks if there is a User-object in the current SessionMap
     * if not, redirects to login page
     *
     * Method is used in layout template
     */
    public void loginCheck() {

        User currentSessionUser = SupportClass.getUserBean().getUser();
        if (currentSessionUser == null) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("login.jsf");
            } catch (IOException ex) {
                Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Checks if input values is correct, if success
     * creates a User-object and puts it into the database
     * redirects to login page
     */
    public String register() {
        errors = new ArrayList<String>();
        boolean success = true;
        if (username.equals("")) {
            errors.add("Username empty");
            success = false;
        } else if (!Mapper.isUsernameUnique(username)) {
            errors.add("Username already exists in database");
            success = false;
        }
        if (password.equals("")) {
            errors.add("Password empty");
            success = false;
        }
        if (email.equals("")) {
            errors.add("Email empty");
            success = false;
        } else if (!Mapper.isEmailUnique(email)) {
            errors.add("Email already exists in database");
            success = false;
        }

        if (success) {
            //Creates user
            User user = new User();
            user.setUsername(username);
            user.setHashedPassword(password);
            user.setEmail(email);
            user.setDate(new Date());
            Rank rank = admin ? Rank.ADMIN : Rank.TRIAL;
            user.setRank(rank);
            //Puts user object into database
            boolean complete = Mapper.registerUser(user);
            if (complete) {
                return "login.jsf";
            } else {
                return "register.jsf";
            }
        } else {
            return "register.jsf";
        }
    }

    /**
     * Destroys the session and redirects to login page
     */
    public String logout() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        session.invalidate();
        return "login.jsf" + "?faces-redirect=true";
    }

    /**
     * Uses Mapper to retrieve a User-object from the database and if success puts the
     * object into the SessionMap
     */
    public String login() {
        errors = new ArrayList<String>();
        User mUser = Mapper.login(username, password);

        if (mUser == null) {
            errors.add("Username or password invalid");
            return "login.jsf";
        } //Else login is OK.. Puts user-object into session
        else {
            UserBean mUserBean = SupportClass.getUserBean();
            mUserBean.setUser(mUser);
            return "index.jsf" + "?faces-redirect=true";
        }
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


}
